package com.GLM.Viewer.Message;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Entity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.GLM.Constants.Constant;
import com.GLM.Entity.MsgEntity;
import com.GLM.Entity.RingEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.RefreshListView.XListView;
import com.GLM.Tools.Utils.RefreshListView.XListView.IXListViewListener;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Circle.CircleDetailMessageActivity;
import com.GLM.Viewer.Customized.Panel;
import com.GLM.Viewer.Customized.Panel.OnPanelListener;
import com.google.gson.Gson;

public class MessageMainActivity extends Activity implements OnPanelListener, IXListViewListener {
	private final static String TAG = "MessageMainActivity";
	private int[] navIds = new int[] { R.string.message_nav01, R.string.message_nav02, R.string.message_nav03, R.string.message_nav04 };
	private Map<String, Integer> navMapping = new HashMap<String, Integer>();
	private int[] messageItemIds = new int[] {  R.id.list_item_nickname, R.id.list_item_date, R.id.list_item_likecount, R.id.list_item_likicon, R.id.list_item_contents,R.id.list_item_messageid };
	private String[] messageItemKeys = new String[] {  "nickname", "date", "likecount", "likeicon", "contents","messageid" };

	private final static int MESSAGE_LOADING = 111;
	private final static int MESSAGE_LONDED = 222;
	AsynImageLoader asynImageLoader = new AsynImageLoader();
	private Panel mSlidingDrawer;
	private XListView mListView;
	private SimpleAdapter mAdapter;
	private Button mTitleView;  
	private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> mListItems = new ArrayList<Map<String,Object>>();
	private ProgressBar mProgressBar;
	private Map<String, String> messagesMap = new HashMap<String, String>();
	private Map<String, String> avatarsMap = new HashMap<String, String>();
	private Map<Integer, Integer> circleMap = new HashMap<Integer, Integer>();
	private int mUserId;
	private int page = 1;
	private String mCurrentTitle;
	private boolean circleTitle = false;
	private int screenWidth;
	private int screenHeight;
	
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			switch (msg.what) {
			case MESSAGE_LOADING:
				page = 1;
				mItems.clear();
				mListView.setAdapter(null);
				mProgressBar.setVisibility(View.VISIBLE);
				thread = new Thread(new Runnable() {
					public void run() {
						initDataItems(navMapping.get(mCurrentTitle));
						mAdapter = initListViewAdapter(navMapping.get(mCurrentTitle));
						mHandler.sendEmptyMessage(MESSAGE_LONDED);
					}
				});
				thread.start();
				break;

			case MESSAGE_LONDED:
				mProgressBar.setVisibility(View.GONE);
				if(mAdapter != null && mItems.size()>0){
					mListView.setAdapter(mAdapter);
					onLoad();
					bindItemClick();
				}else{
//					Paint paint = new Paint();
//					paint.setTextSize(20);
//					paint.setAntiAlias(true);
//					String str = getString(R.string.message_no_mymsg);
//					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
//					Canvas canvas = new Canvas(bitmap);
//					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
//					FrameLayout layout = (FrameLayout)findViewById(R.id.message_layout);
//					Drawable drawable = new BitmapDrawable(bitmap);
//					layout.setBackgroundDrawable(drawable);
				}
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		setContentView(R.layout.view_message);
		initNavMapping();
		mUserId = UserInfoDAO.getUserInfo(this).getUserId();
		mCurrentTitle = getString(R.string.message_nav02);
		initSlidingDrawer();
		mTitleView = (Button) findViewById(R.id.message_title);
		mTitleView.setText(mCurrentTitle);
		final SharedPreferences sp = getSharedPreferences(Constant.SHAREDNAME, MODE_PRIVATE);
		boolean isshow = sp.getBoolean(Constant.MESSAGEACTIVITY, true);
		final ImageView tipView = (ImageView)findViewById(R.id.tipView);
		if(!isshow){
			tipView.setVisibility(View.VISIBLE);
			tipView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					tipView.setVisibility(View.INVISIBLE);
					tipView.setImageBitmap(null);
					Editor editor = sp.edit();
					editor.putBoolean(Constant.MESSAGEACTIVITY, true);
					editor.commit();
					System.gc();
					return true;
				}
			});
		}
		initListView();
		
	}

	private void initNavMapping() {
		String key = getString(R.string.message_nav01);
		navMapping.put(key, Constant.REQ_WAY_MESSAGE_RING);
		key = getString(R.string.message_nav02);
		navMapping.put(key, Constant.REQ_WAY_MESSAGE_MY);
		key = getString(R.string.message_nav03);
		navMapping.put(key, Constant.REQ_WAY_LOOKAROUND);
		key = getString(R.string.message_nav04);
		navMapping.put(key, Constant.REQ_WAY_MERCHANT);

	}

	private void initListView() {
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar_firstload);
		if (mItems == null || mItems.size() == 0) {
			mHandler.sendEmptyMessage(MESSAGE_LOADING);
		}
		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				MsgEntity entity = (MsgEntity) item.get("entity");
				Intent intent = null;
				switch (navMapping.get(mCurrentTitle)) {
				case Constant.REQ_WAY_MESSAGE_MY:
					intent = new Intent(MessageMainActivity.this, MessageDetailActivity.class);
					intent.putExtra(Constant.MESSAGE_CURRENT_USERID, mUserId);
					intent.putExtra(Constant.MESSAGE_ENTITY, entity);
					startActivity(intent);
					Log.v(TAG, "click one ->" + entity.getMsg_content());
					break;
				case Constant.REQ_WAY_LOOKAROUND:
					break;
				case Constant.REQ_WAY_MESSAGE_RING:
					break;
				case Constant.REQ_WAY_MERCHANT:
					break;
				default:
					break;
				}
			}
		});
	}

	private void initSlidingDrawer() {
		
		mSlidingDrawer = (Panel) findViewById(R.id.glmSlidingdrawer);
		
		mSlidingDrawer.setOnPanelListener(this);
		List<Map<String, Object>> items = initGridViewItems();
		GridView gv = (GridView) findViewById(R.id.mycontent);
		gv.setAdapter(new SimpleAdapter(this, items, R.layout.view_navgrid, new String[] { "key" }, new int[] { R.id.navgrid_button }));
		gv.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(position == 0){
					circleTitle = true;
				}else{
					circleTitle = false;
				}
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				if (mSlidingDrawer.isOpen()) {
					mCurrentTitle = (String) item.get("key");
					mTitleView.setText(mCurrentTitle);
					mSlidingDrawer.setOpen(false, true);
					mHandler.sendEmptyMessage(MESSAGE_LOADING);
				}
			}
		});
	}

	private List<Map<String, Object>> initGridViewItems() {
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < navIds.length; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("key", getString(navIds[i]));
			listItems.add(item);

		}
		return listItems;
	}

	public void titleOnClick(View v){
		final FrameLayout circleLayout = (FrameLayout)findViewById(R.id.circle_msg_layout);
		if(circleTitle){
			Log.d("circleTitleTrue_onclick", "circleTitleTrue_onclicked");
			circleLayout.setVisibility(View.VISIBLE);
			final ListView mCircleListView = (ListView)circleLayout.findViewById(R.id.msg_circle_list);
			circleMap.clear();
			mListItems.clear();
			initMyCircleList();
			SimpleAdapter adapter = new SimpleAdapter(MessageMainActivity.this, mListItems, R.layout.view_message_circlelist_item, new String[]{"circleName"}, new int[]{R.id.message_circle_text});
			mCircleListView.setAdapter(adapter);
			
			mCircleListView.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent,
						View view, int position, long id) {
					// TODO Auto-generated method stub
					circleLayout.setVisibility(View.INVISIBLE);
					page = 1;
					
					mItems.clear();
					avatarsMap.clear();
					messagesMap.clear();
					int ringId = circleMap.get(position);
					initCircleMessage(ringId);
					mAdapter = new SimpleAdapter(MessageMainActivity.this, mItems, R.layout.xlistview_item_message, messageItemKeys, messageItemIds);
					mListView.setAdapter(mAdapter);
				}
			});
		}
	}
	
	
	public void initCircleMessage(int ringid){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String currentDate = sDateFormat.format(new java.util.Date());
		JSONObject request = new JSONObject();
		try {
			request.put("class", 1);
			request.put("msg_page", page);
			request.put("msg_date", currentDate);
			request.put("ring_id", ringid);
			JSONResponse jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETCIRCLEMESSAGE, request);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					initMessageItemFromJSONObject(data.getJSONArray("msgData"));
				} else {
					ViewsUtil.showErrorTip(MessageMainActivity.this, R.string.message_nomsg_toload);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public void bindItemClick(){
		mListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v, int position,
					long arg3) {
				// TODO Auto-generated method stub
				
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				MsgEntity entity = (MsgEntity) item.get("entity");
				int msg_userid = (Integer) item.get("userid");
				Intent intent = new Intent(MessageMainActivity.this,MessageDetailActivity.class);
				intent.putExtra(Constant.MESSAGE_CURRENT_USERID, msg_userid);
				intent.putExtra(Constant.MESSAGE_ENTITY, entity);
				startActivity(intent);
			}
		});
		mListView.setOnScrollListener(scrollListener);
	}
	
	public OnScrollListener  scrollListener = new OnScrollListener() {
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if(visibleItemCount >0 && totalItemCount >0){
				LoadPic();
			}
				
		}
	};
	
	
	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}

	private SimpleAdapter initListViewAdapter(int reqWay) {
		SimpleAdapter adapter = null;
		switch (reqWay) {
		case Constant.REQ_WAY_MESSAGE_MY:
		case Constant.REQ_WAY_LOOKAROUND:
		case Constant.REQ_WAY_MESSAGE_RING:
			adapter = new SimpleAdapter(MessageMainActivity.this, mItems, R.layout.xlistview_item_message, messageItemKeys, messageItemIds);
			break;
		case Constant.REQ_WAY_MERCHANT:
			break;
		default:
			break;
		}
		return adapter;
	}

	private void initDataItems(int reqWay) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String currentDate = sDateFormat.format(new java.util.Date());
		JSONObject request = new JSONObject();
		try {
			request.put(Constant.PARAM_LOOKAROUND_PAGE, page);
			request.put(Constant.PARAM_LOOKAROUND_DATE, currentDate);
			request.put(Constant.PARAM_USERID, mUserId);
			Log.d("jsonRequest", request.toString());
			JSONResponse jsonResponse = JSONUtil.postRequest(reqWay, request);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					initItemFromJSONObject(reqWay, data);
				} else {
//					ViewsUtil.showErrorTip(MessageMainActivity.this, R.string.global_error_networkerr);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		navMapping.put(mCurrentTitle, reqWay);
	}

	public void initMyCircleList(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID, mUserId);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETMYCIRCLELIST, jsonData);

			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_RING_LIST);
					initMyCircleListItemFromJSONObject(jsonArray);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
	
	private void initMyCircleListItemFromJSONObject(JSONArray jsonArray) throws JSONException {
		Gson gson = new Gson();
		
		for (int i = 0; i < jsonArray.length(); i++) {
			RingEntity ringEntity = gson.fromJson(jsonArray.getJSONObject(i).toString(), RingEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("circleName", ringEntity.getRing_name());
			mListItems.add(item);
			circleMap.put(i, ringEntity.getRing_id());
		}
	}

	private void initItemFromJSONObject(int reqWay, JSONObject data) throws JSONException {
		JSONArray jsonArray = null;
		switch (reqWay) {
		case Constant.REQ_WAY_MESSAGE_MY:
			jsonArray = data.getJSONArray(Constant.RESP_MESSAGE_MYMSG);
			initMessageItemFromJSONObject(jsonArray);
			break;
		case Constant.REQ_WAY_LOOKAROUND:
			jsonArray = data.getJSONArray(Constant.RESP_ALLMSG);
			initMessageItemFromJSONObject(jsonArray);
			break;
		case Constant.REQ_WAY_MESSAGE_RING:
			jsonArray = data.getJSONArray(Constant.RESP_MESSAGE_RINGMSG);
			initMessageItemFromJSONObject(jsonArray);
			break;
		case Constant.REQ_WAY_MERCHANT:
			break;
		default:
			break;
		}

	}

	public void LoadPic(){
		int count = mListView.getChildCount();
		for(int i=0; i<count; i++){
			View view = mListView.getChildAt(i);
			ImageView avatarView = (ImageView)view.findViewById(R.id.list_item_avatar);
			ImageView commentView = (ImageView)view.findViewById(R.id.list_comment_imageview);
			TextView messageIdView = (TextView)view.findViewById(R.id.list_item_messageid);
			String avatarUrl = null;
			String commentUrl = null;
			if(messageIdView != null){
				Log.d("commentViewtext", messageIdView.getText().toString()+"");
				avatarUrl = avatarsMap.get(messageIdView.getText());
				commentUrl = messagesMap.get(messageIdView.getText());
			}
			if(avatarUrl != null && !avatarUrl.equals("")){
				Log.d("avatarUrl", avatarUrl);
				asynImageLoader.showImageAsyn(avatarView, Constant.URL_USER_SMALL+avatarUrl, R.drawable.glm_white);
			}
			if(commentUrl != null && !commentUrl.equals("")){
				Log.d("commentUrl", commentUrl+"");
				if(commentView.getVisibility() == View.GONE)
					commentView.setVisibility(View.VISIBLE);
				asynImageLoader.showImageAsyn(commentView, Constant.URL_MESSAGEPIC_SMALL+commentUrl, R.drawable.glm_white);
			}
			else{
//				if(commentView.getVisibility() == View.VISIBLE)
//					commentView.setVisibility(View.GONE);
			}
			
		}
	}
	
	private void initMessageItemFromJSONObject(JSONArray jsonArray) throws JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			MsgEntity msgEntity = gson.fromJson(jsonArray.getJSONObject(i).toString(), MsgEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String avatarPath = msgEntity.getMsg_user_avatar();
			
			item.put("nickname", msgEntity.getMsg_user_nickname());
			item.put("date", msgEntity.getMsg_date());
			if (0 == msgEntity.getMsg_viewCount()) {
				item.put("likeicon", R.drawable.glm_likeicon_dark);
			} else {
				item.put("likeicon", R.drawable.glm_likeicon_red);
			}
			item.put("likecount", String.format("Like: %d", msgEntity.getMsg_viewCount()));
			item.put("contents", msgEntity.getMsg_content());
			item.put("entity", msgEntity);
			item.put("userid", msgEntity.getMsg_user_id());
			item.put("messageid", msgEntity.getMsg_id());
			mItems.add(item);
			avatarsMap.put(String.valueOf(msgEntity.getMsg_id()), avatarPath);
			
			String comPic = msgEntity.getMsg_picture();
			Log.d("CircleDetailPicUrl", comPic+"");
			messagesMap.put(String.valueOf(msgEntity.getMsg_id()), comPic);
		}
	}

	public void goBackButton_OnClick(View v) {
		NavUtils.navigateUpFromSameTask(this);
	}

	public void onPanelClosed(Panel panel) {

	}

	public void onPanelOpened(Panel panel) {

	}

	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			public void run() {
				page = 1;
				mItems.clear();
				avatarsMap.clear();
				messagesMap.clear();
				initDataItems(navMapping.get(mCurrentTitle));
				mAdapter = initListViewAdapter(navMapping.get(mCurrentTitle));
				mListView.setAdapter(mAdapter);
				onLoad();
			}
		}, 2000);
	}

	public void onLoadMore() {
		page += 1;
		mHandler.postDelayed(new Runnable() {
			public void run() {
				initDataItems(navMapping.get(mCurrentTitle));
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}
}
